<?php if(!defined('FRAME')) exit('No direct script access allowed');
/**
 * 配置
 * @author wisoch@hotmail.com
 *
 */
class Config {

	private static $instance;

	private $config = array();

	private $_separator = '.';

	public static function Instance() {
        if( ! (self::$instance instanceof self) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 设置
     * @param array $config
     */
	public function set($config) {
		$pasered = $this->paserConfig($config);
		$this->config = array_merge($this->config, $pasered);
		return $this;
	}

	/**
	 * 获取配置
	 * @param string $key
	 */
	public function get($key = '') {
		if($key) {
			$arr = explode($this->_separator, $key);
			$return = $this->config;
			foreach ($arr as $key => $value) {
				if(isset($return[$value])) $return = $return[$value];
				else return null;
			}
			return $return;
		} else {
			return $this->config;
		}
	}

	/**
	 * 解析配置
	 * @params array|string $config
	 */
	private function paserConfig($config) {
		$conf = array();
		foreach($config as $key => $value) {
			//$key = strtolower($key);
			$tmp = array();
			if(count($key_tmp = explode($this->_separator, $key)) > 1) {
				if(is_array($value)) {
					$value = $this->paserConfig($value);
				} 
				$tmp[array_pop($key_tmp)] = $value;
				$key_tmp = array_reverse($key_tmp);
				foreach($key_tmp as $vt) {
					$tmp[$vt] = $tmp;
					array_shift($tmp);
				}
			} else {
				if(is_array($value)) {
					$tmp[$key] = $this->paserConfig($value);
				} else {
					$tmp[$key] = $value;
				}
			}
			$conf = array_merge_recursive($conf, $tmp);
		}
		return $conf;
	}

	/**
	 * 加载配置
	 * @params array|string $ini
	 */
	public function loadIni($ini) {
		if(is_string($ini)) {
			if(!file_exists($ini)) trigger_error("Cannot load config file:$ini", E_USER_WARNING);
			$this->set(parse_ini_file($ini, true));
		} else {
			foreach($ini as $v) {
				if(!file_exists($v)) trigger_error("Cannot load config file:$v", E_USER_WARNING);
				$this->set(parse_ini_file($v, true));
			}
		}
		return $this;
	}
}